layui.use(['element', 'code', 'backend', 'form'], function(){
    var element = layui.element,
        $ = layui.jquery,
        form = layui.form,
        backend = layui.backend,
        code = layui.code;

    layui.code({
        title: 'json'
    });

    form.on('submit(api-send)', function(data){
        var header = form.val("header");
        var api = form.val("api");
        backend.api.ajax({
            url : data.form.action,
            type : data.form.method,
            headers: header,
            data : api,
        }, function (data, ret) {
            $("#api_data").text(JSON.stringify(ret, null, 4));
            return false;
        }, function (data, ret) {
            $("#api_data").text(JSON.stringify(ret, null, 4));
            return false;
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
    form.on('reset(api-send)', function () {
        alert(1);
    })

    function formToArray(arr) {
        var obj = {};
        for(var i in arr) {
            var key = arr[i].name;
            var val = arr[i].value;
            var index = key.indexOf("[");
            if(index > -1) {
                // 获取 Keys
                var keys = [];
                keys.push(key.substr(0, index)); // 第一个
                var reg = /\[(.+?)\]/g;
                var iarr = key.match(reg);
                for(var ia in iarr) {
                    keys.push(iarr[ia].substr(1, iarr[ia].length - 2));
                }
                var keyCount = keys.length;

                // 循环写入值
                var cur = undefined;
                for(var ik in keys) {
                    var k = keys[ik];
                    if(cur === undefined) {
                        if(obj[k] === undefined) {
                            obj[k] = {};
                        }
                        cur = obj[k];
                    } else {
                        if(cur[k] === undefined) {
                            cur[k] = {};
                        }
                        if(ik > (keyCount - 2)) {
                            cur[k] = val;
                        } else {
                            cur = cur[k];
                        }
                    }
                }
                cur = val;

            } else {
                obj[key] = val;
            }
        }
        return obj;
    }
});
